package it.sandler.android.database;

/**
 * You can do what ever you want to do with SandlerDB.<br>
 * There are no restrictions. You can use SandlerDB for commercial use.<br>
 * <br>
 * Circle me on Google+: http://gplus.to/roberthahn<br>
 * SandlerDB on Google Code: http://code.google.com/p/sandler-db-for-android/<br>
 * <br>
 * Date: 04/16/2012
 * 
 * @author Robert Hahn
 * 
 */
public class SandlerRelationTable extends SandlerBaseTable {

	private final Class<?> firstClass;
	private final Class<?> secondClass;

	protected SandlerRelationTable(Class<?> firstClass, Class<?> secondClass) {
		// make sure the table always has the same format
		if (firstClass.getSimpleName().toLowerCase()
				.compareTo(secondClass.getSimpleName().toLowerCase()) < 0) {
			this.firstClass = firstClass;
			this.secondClass = secondClass;
		} else {
			this.firstClass = secondClass;
			this.secondClass = firstClass;
		}
	}

	/**
	 * Generates the CREATE TABLE Statement
	 * 
	 * @return
	 */
	@Override
	protected String create() {
		String c = "\"___id___\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ___dummy___ INTEGER, ";
		c += "\"first___" + firstClass.getSimpleName()
				+ "___id\" INTEGER(64), ";
		c += "\"second___" + secondClass.getSimpleName()
				+ "___id\" INTEGER(64)";
		return "CREATE TABLE " + getTableName() + " (" + c + ");";
	}

	protected String getFirstFieldName() {
		return "first___" + firstClass.getSimpleName() + "___id";
	}

	protected String getSecondFieldName() {
		return "second___" + secondClass.getSimpleName() + "___id";
	}

	/**
	 * Generates the Table DROP Statement
	 * 
	 * @return
	 */
	@Override
	protected String drop() {
		return "DROP TABLE IF EXISTS " + getTableName();
	}

	protected String getTableName() {
		return firstClass.getSimpleName() + "Has" + secondClass.getSimpleName();
	}

	public String getFieldName(Class<? extends SandlerEntity> class1) {
		return class1.getSimpleName().equals(firstClass.getSimpleName()) ? getFirstFieldName()
				: getSecondFieldName();
	}

}
